--[[
-- @Author:      feilong
-- @DateTime:    2020-11-13 23:05:48
-- @Description: redis消息的处理
-- @Example:
	local data = g.Message():callService(".redis", "redis_cmd", nil, "get", "num")
	g.log:debug("redis data", data)


--]]
local redis = require("skynet.db.redis")
local skynet_queue = require("skynet.queue")

local table_remove = table.remove
local table_insert = table.insert
local debug = debug


local M = class("Hander")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function M:ctor()
    local server_config = g.getServerConf()
    local conf = server_config.redis
    self.db_info = {
        host = conf.host,
        port = conf.port,
        db = conf.db_id,
        auth = conf.password,
    }
    if self.db_info.auth == "" then
        self.db_info.auth = nil
    end

    self.conn = nil

    self:register()
end

--注册本服务里的消息
function M:register()
    g.dispatch:registerDefault(handler(self,self.defaultCommand))
end

--从连接池里取一个服务
function M:getConnect()    
    if self.conn then
        return self.conn
    end
    local redis_conf = self.db_info
    local ok,ret = xpcall(redis.connect, debug.traceback, redis_conf)
    while not ok do
        g.log:error('failed to connect redis',ret)
        g.sleep(500)   --one second
        ok,ret = xpcall(redis.connect, debug.traceback, redis_conf)
    end
    self.conn = ret
    return ret
end


---------------------------------------------------------
-- CMD
---------------------------------------------------------

function M:normalCommand(cmd, ...)
    -- body
    local conn = self:getConnect()
    local func = conn[cmd]
    local ok, ret = xpcall(func, debug.traceback, conn, ...)
    while not ok do
        g.log:error("redis错误:", ret, cmd, ...)
        g.sleep(300)
        print('send to redis err now retry....')
        ok,ret = xpcall(func, debug.traceback, conn, ...)
    end
    if not ok then
        g.log:error(ret)
    end
    return ret
end


function M:defaultCommand(cmd, ...)
    return self:normalCommand(cmd, ...)
end





return M